/**
 * Created by wangjunwei on 2018/11/08.
 */
//Model Control 合起来了
/*
required string Code 				=1;	//道具Code
required string Name 				=2;	//道具名称
required string CustomName 			=3;  //自定义名称
required string TagType 			=4;	//道具背包页签分类
optional string ImgBig 				=5;	//大图片
optional string ImgMid 				=6;	//中图片
optional string ImgSml 				=7;	//小图片
optional string	Describe			=8;	//道具说明
required int32	AvailableOn 		=9;	//道具生效依赖  数量:0、时间:1 保留时间（非装备或不使用状态下，道具剩余时间不消耗）:2
optional int32 SuperPositionType	=11;	//叠加方式，累加：0，覆盖：1
optional int32 Status				=12;	//状态，作废：0
optional string	ExtraInfo 			=13;	//额外信息
required int32 NatureType           =14;   //道具类型		2:礼包、3：道具 4：话费
optional int32 BagDisplay           =15;   //背包是否显示
optional int32 FaceValue            =16;   //话费面值，单位分
*/

ItemData = {
    m_itemData: [],
    m_Proto_Table: [],
    ItemChangeTable: [],
    m_EmailRed: false,

    loadAllProto: function () {
        var that = this;
        //protobuf路径 和 package名称
        var ProtoPath = ["modules/main/hall_common_module/src/BagLayer/Item.proto",
            'modules/main/hall_common_module/src/RedBagLayer/RedPacket.proto',
            'modules/main/hall_common_module/src/TicketShopLayer/FishMallPB.proto',
            'modules/main/hall_common_module/src/EmailLayer/interface.proto'];
        var ProtoName = ['Item', 'RedPacket', 'FishMallPB', 'interface'];


        for (var i = 0; i < ProtoName.length; i++) {
            (function (i) {
                cc.loader.loadTxt(ProtoPath[i], function (err, txt) {
                    var name = ProtoName[i];
                    var ProtoBuf = dcodeIO.ProtoBuf;
                    mProto.builder[name] = ProtoBuf.loadProto(txt);
                    mProto.initCommonModule(name);
                    if (ProtoName[i] == "Item") {
                        that.getAllItemConfig();
                    }
                    if (ProtoName[i] == "interface") {
                        that.addSysEmail(); //加入系统邮件 登录就要获取 无实际数据
                    }
                });
            })(i);
        }
    },
    //获取Item 所有配置
    getAllItemConfig: function (refresh) {
        var that = this;
        var _version = parseInt(cc.sys.localStorage.getItem('Item_Version')) || 0;
        if (refresh) {
            _version = 0;
        }
        var data = {
            UserID: gameData.uid + "",
            AppID:app.appId + "",
            ConfigVersion: _version,
            notice_ip: "",
            notice_port: 0
        };


        network.addListener(1058, function (data) {
            var ConfigList = data.ConfigList; //道具列表
            if (ConfigList.length == 0) {
                that.m_itemData = JSON.parse(cc.sys.localStorage.getItem('ItemAllConfig'));
            } else {
                cc.sys.localStorage.setItem('Item_Version', data.ConfigVersion);//当前配置的版本号
                cc.sys.localStorage.setItem('ItemAllConfig', JSON.stringify(ConfigList));
                that.m_itemData = ConfigList;
            }
            if (!refresh){ //只执行一次 防止卡死
                that.judgeSmallImg(); // todo 判断是否有小图 否则重新请求
            }
        })
        network.sendProto(1057, data);
    },

    judgeSmallImg: function () {
        var that = this;
        for (var i = 0; i < that.m_itemData.length; i++) {
            if (!that.m_itemData[i].ImgSml || that.m_itemData[i].ImgSml == ""){ //小图不存在 重新请求
                that.getAllItemConfig(true);
                break;
            }
        }
    },
    //将系统邮件加入到邮箱里 客户端主动拉取
    addSysEmail: function () {
        var that = this;
        var data = {
            userid: gameData.uid + "",
            gameid: app.area + "",
        };

        network.addListener(1032, function (data) {

        });
        network.sendProto(1031, data);

    },

    getItemInfoByCode: function (code) {
        var that = this;
        for (var i = 0; i < that.m_itemData.length; i++) {
            if (that.m_itemData[i].Code == code) {
                return that.m_itemData[i];
            }
        }
        return null;
    },

    setItemChange: function (_changeTable) {
        var that = this;
        that.ItemChangeTable = [];
        var tagTypeT = ['item', 'bill', 'tickets'];
        for (var i = 0; i < _changeTable.length; i++) {
            var _itemInfo = ItemData.getItemInfoByCode(_changeTable[i].Code);
            if (_itemInfo.TagType == tagTypeT[0] || _itemInfo.TagType == tagTypeT[1] || _itemInfo.TagType == tagTypeT[2]) {
                that.ItemChangeTable.push(_changeTable[i]);
            }
        }
    },

    getItemChange: function () {
        return this.ItemChangeTable || [];
    },
    getTagTypeByCode: function (code) {
        var that = this;
        for (var i = 0; i < that.m_itemData.length; i++) {
            if (that.m_itemData[i].Code == code) {
                return that.m_itemData[i].TagType;
            }
        }
        return null;
    }
};


var loadUrlImageToSprite = function (url, targetSprite) {
    if (url.charAt(url.length - 2) == '/' &&
        url.charAt(url.length - 1) == '0')
        url = url.substr(0, url.length - 2) + '/132';

    cc.textureCache.addImageAsync(url, function (texture) {
        targetSprite.removeAllChildren();
        if (!targetSprite.getChildByName('Image')) {
            var sprite = new cc.Sprite(texture);
            sprite.setTexture(texture);
            sprite.setAnchorPoint(0.5, 0.5);
            sprite.setPosition(0, 0);
            sprite.setName('Image');
            targetSprite.addChild(sprite);
        } else {
            targetSprite.getChildByName('Image').setTexture(texture);
        }
    }, null);
};


